package fr.demos.cinepantin.dao.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.UserTransaction;

import fr.demos.cinepantin.Film;
import fr.demos.cinepantin.Livre;

import fr.demos.cinepantin.dao.DaoFilm;
import fr.demos.cinepantin.dao.interfac.FilmDao;
import fr.demos.cinepantin.exception.DaoExceptions;

@DaoFilm
public class FilmDaoImpl implements FilmDao {
	// Grace a l'injection l'objet entityManager est instancie
	@PersistenceContext(unitName = "cinemarc")
	private EntityManager em; // gestion des entity qui sont dans un contexte
	@Resource
	private UserTransaction ut;

	@Override
	public List<Film> getAllFilm() throws DaoExceptions {

		Film film = null;
		String query = "select f from Film f ";
		TypedQuery<Film> q = em.createQuery(query, Film.class);
		List<Film> resFilm = q.getResultList();

		return resFilm;

	}


	@Override
	public Film getFilmById(int id) throws DaoExceptions {	
		Film film = null;
		film = em.find(Film.class, id);

		return film;


	}

	@Override
	public List<Film> getFilmByTitre(String titre) throws DaoExceptions {
		
		String query = "SELECT f FROM Film f WHERE";
		query += " titre LIKE '%" + titre + "%'";
		TypedQuery<Film> q = em.createQuery(query, Film.class);
		List<Film> resFilm = q.getResultList();
		return resFilm;

	}

	@Override
	public List<Film> getFilmByRealisateur(String realisateur)
			throws DaoExceptions {
		
		String query = "SELECT f FROM Film d WHERE";
		query += " realisateur LIKE '%" + realisateur + "%'";
		TypedQuery<Film> q = em.createQuery(query, Film.class);
		List<Film> resFilm = q.getResultList();
		return resFilm;

	}

	@Override
	public void addFilm(Film f) throws DaoExceptions {
		// TODO Auto-generated method stub
		try {
			ut.begin();
		} catch (Exception e) {
			e.printStackTrace();
		}

		em.persist(f);

		try {
			ut.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new DaoExceptions(e.getMessage(), e);
		}
	}


	@Override
	public List<Film> getFilmByIdArticle(int idArticle) throws DaoExceptions {
		// TODO Auto-generated method stub
		return null;
	}
		
	}


